<?php

namespace App\Http\Controllers\Api\v1\User;

use App\Exceptions\ApiException;
use App\Http\Controllers\Api\BaseController;
use App\Models\Api\AstroSetting;

use DB,Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;

class AstrosetController extends BaseController
{
    /**
     * 获取星盘配置
     * @method GET
     * @return \response\Json
     */
    public function index(Request $request)
    {
        if (!$request->isMethod('get'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = $request->all();

        $validate = new \App\Tools\Validates\Astroset();

        if (!$validate->scene('index')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $map = ['uid' => $request->uid, 'chart' => $param['chart'], 'tid' => $param['tid']];

        $AstrosetModel = new AstroSetting();

        $setting = $AstrosetModel->getUserSettingByTid($map);

        $data = $setting[$param['chart']];

        if (isset($setting['is_default']))
        {
            $data['is_default'] = $setting['is_default'];
        } else
        {
            $data['is_default'] = false;
        }

        if (isset($setting['id']))
        {
            $data['id'] = $setting['id'];
        }

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 更新星盘配置
     * @method POST
     * @return \think\response\Json
     */
    public function update(Request $request)
    {
        if (!$request->isMethod('post'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = $request->all();

        $decodeValue = json_decode($param['chart_value'],true);

        if($param['chart'] === 'firdaria' && !isset($decodeValue['firdaria']))
        {
            $decodeValue['firdaria'] = 'default';
        }

        $param['chart_value'] = json_encode($decodeValue,true);

        $validate = new \App\Tools\Validates\Astroset();

        if (!$validate->scene('update')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $param['uid'] = $request->uid;

        if (!(new AstroSetting())->updateUserSetting($param))
        {
            return show(config('code.error'), '更新配置失败');
        }

        return show(config('code.success'), '更新配置成功');
    }

    /**
     * 还原星盘配置
     * @method DELETE
     * @return \think\response\Json
     */
    public function restore(Request $request)
    {
        if (!$request->isMethod('put'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = $request->all();

        $validate =new \App\Tools\Validates\Astroset();

        if (!$validate->scene('delete')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $param['uid'] = $request->uid;

        if (!(new AstroSetting())->restoreUserSetting($param))
        {
            return show(config('code.error'), '还原失败');
        }

        return show(config('code.success'), '还原成功');
    }

    /**
     * 用户配置初始化
     * @throws ApiException
     */
    public function init($uid = NULL)
    {
        if (!$uid)
        {
            $uid = $request->uid;
        }
        $time = time();

        $exist_count = (new AstroSetting())->where(['uid' => $uid])->count('id');

        if ($exist_count >= 3)
        {
            throw new ApiException('初始化已完成', 200, config('code.error'));
        }

        $setting1 = config('astroset.setting1');
        foreach ($setting1 as $k1 => $item1)
        {
            if (in_array($k1, config('astroset.chart'))) $setting1[$k1] = json_encode($item1);
        }
        $setting1['create_time'] = $time;
//        $setting1['update_time'] = $time;
        $setting1['use_time'] = $time;
        $setting1['tid'] = 1;
        $setting1['uid'] = $uid;

        $setting2 = config('astroset.setting2');
        foreach ($setting2 as $k2 => $item2)
        {
            if (in_array($k2, config('astroset.chart'))) $setting2[$k2] = json_encode($item2);
        }
        $setting2['create_time'] = $time;
//        $setting2['update_time'] = $time;
        $setting2['use_time'] = $time;
        $setting2['tid'] = 2;
        $setting2['uid'] = $uid;

        $setting3 = config('astroset.setting3');
        foreach ($setting3 as $k3 => $item3)
        {
            if (in_array($k3, config('astroset.chart'))) $setting3[$k3] = json_encode($item3);
        }
        $setting3['create_time'] = $time;
//        $setting3['update_time'] = $time;
        $setting3['use_time'] = $time;
        $setting3['tid'] = 3;
        $setting3['uid'] = $uid;

        (new AstroSetting())->insertGetId($setting1);
        (new AstroSetting())->insertGetId($setting2);
        (new AstroSetting())->insertGetId($setting3);
    }
/**
     * 获取当前使用的星盘配置方案
     * @param bool $is_in
     * @param string $chart
     * @return array|false|\PDOStatement|string|\think\Model|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function get($is_in = false, $chart = '', $default = false,$tid=0)
    {
        $uid = $request->uid;
        $chart = $chart == '' ? htmlspecialchars(request()->input('chart')) : $chart;
        $tid = $tid == 0 ? request()->input('tid',0) : $tid;

        if (!in_array($chart, config('astroset.chart')))
        {
            throw new ApiException('星盘类型不存在', 200, config('code.error'));
        }

        if ($default === true)
        {
            if ($tid = 2) $setting = config('astroset.setting2')[$chart];
            elseif ($tid = 3) $setting = config('astroset.setting3')[$chart];
            else $setting = config('astroset.setting1')[$chart];
            return ['value' => $setting];
        }

        if($tid >= 1 && $tid <= 3)
        {
            $setting = AstroSetting::select('id','uid','use_time','update_time','tid',$chart)
                ->where(['uid'=>$uid,'tid'=>$tid])
                ->first();
        }
        else
        {
            $setting = AstroSetting::select('id','uid','use_time','update_time','tid',$chart)
                ->where(['uid'=>$uid])
                ->orderBy('use_time','DESC')
                ->first();
        }


        if(empty($setting))
        {
            $this->init($uid);

            if($tid >= 1 && $tid <= 3)
            {
                $setting = AstroSetting::select('id','uid','use_time','update_time','tid',$chart)
                    ->where(['uid'=>$uid,'tid'=>$tid])
                    ->first();
            }
            else
            {
                $setting = AstroSetting::select('id','uid','use_time','update_time','tid',$chart)
                    ->where(['uid'=>$uid])
                    ->orderBy('use_time','DESC')
                    ->first();
            }
        }

//        //缓存用户自定义星盘配置
//        $setting = $this->AstroSettingModle->get_user_setting(['tid' => $tid, 'uid' => $uid, 'chart' => $chart]);

        if (empty($setting))
        {
            throw new ApiException('获取星盘配置失败', 200, config('code.error'));
        }
        // 若为空 触发更新当前所有为null的
        if ($setting[$chart] == NULL)
        {
            if ($setting['tid'] == 1) $setting[$chart] = json_encode(config('astroset.setting1')[$chart]);
            elseif ($setting['tid'] == 2) $setting[$chart] = json_encode(config('astroset.setting2')[$chart]);
            elseif ($setting['tid'] == 3) $setting[$chart] = json_encode(config('astroset.setting3')[$chart]);
            if ($setting[$chart]) AstroSetting::where(['uid' => $uid, 'tid' => $setting['tid']])
                ->update([$chart => $setting[$chart]]);
        }
        $setting['value'] = json_decode($setting[$chart], true);
//        unset($setting[$chart]);
        // 更新当前配置使用时间
//         Db::table('app_astro_setting')->where('id',$setting['id'])->setField('use_time',time());
        if ($is_in === true) return $setting;// 内部调用 返回
        return show(config('code.success'), '加载成功', $setting);
    }
   /**
     * 更新配置
     * @return mixed
     * @throws ApiException
     */
    public function set(Request $request)
    {
        $id    = $request->input('id');
        $tid   = $request->input('tid');
        $uid   = $request->uid;
        $chart = htmlspecialchars($request->input('chart'));
        if (!in_array($chart, config('astroset.chart'))) {
            throw new ApiException('星盘类型不存在', 200, config('code.error'));
        }
        $set = $request->input('chart_value');

        $setArr = json_decode($set, true);
        if (!isset($setArr['asp_orb_all'])
            || !isset($setArr['asps_display'])
            || !isset($setArr['planets_display'])
            || !isset($setArr['planet_orb_all'])
            || !isset($setArr['h_sys'])
            || count($setArr['asp_orb_all']) != 11
            || strlen($setArr['planets_display']) != 21
            || count($setArr['planet_orb_all']) != 10
            || strlen($setArr['h_sys']) != 1
            || substr($setArr['planets_display'], 0, 10) != '1111111111'
        ) {
            return show(config('code.error'), '参数错误');
        }

        $data = json_encode($setArr);

        $time = time();

         try
        {
            DB::table('astro_setting')
                ->where(['id' => $id, 'uid' => $uid, 'tid' => $tid])
                ->update([$chart => $data, 'update_time' => $time, 'use_time' => $time]);
        } catch (\Exception $e)
        {

            throw new ApiException('更新失败', 200, config('code.error'));
        }


        $this->rm_cache(['uid'=>$uid,'chart'=>$chart,'tid'=>$tid]);

        return show(config('code.success'), '更新成功');
    }

    /**
     * 更换要使用的方案
     * @throws ApiException
     */
    public function used(Request $request)
    {
        $tid = $request->input('tid');

        $uid = $request->uid;

        try
        {
            AstroSetting::where(['tid' => $tid, 'uid' => $uid])->update(['use_time'=>time()]);
        } catch (\Exception $e) {

            throw new ApiException('切换失败', 200, config('code.error'));
        }

        return show(config('code.success'), '切换成功');
    }
     public function rm_cache($map=[])
    {
        $uid = $map['uid'];
        $chart = $map['chart'];
        $tid = $map['tid'];

        Cache::forget('user_astro_setting_'.$uid.'-'.$chart.'-'.$tid);
    }
}
